package com.mingyizhudao.app.view.notify;

import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.app.IntentService;
import android.app.Service;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import com.alipay.euler.andfix.patch.PatchManager;
import com.dixiang.framework.R;
import com.dixiang.framework.utils.AlertDialogs;
import com.mingyizhudao.app.utils.CommonUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

/**
 * An {@link IntentService} subclass for handling asynchronous task requests in
 * a service on a separate handler thread.
 * <p/>
 * TODO: Customize class - update intent actions, extra parameters and static
 * helper methods.
 */
public class UpdateIntentService extends IntentService {

    private final static String KEY_DOWNLOAD_URL = "download_url";
    private final static String PATCH = "myzd";
    private final static String FILE_NAME="apppatch.apatch";
    private final static String TAG = "UpdateIntentService";
    public UpdateIntentService() {
        super("UpdateIntentService");
        Log.i("====", "=>UpdateIntentService");
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        String urlStr = intent.getStringExtra(KEY_DOWNLOAD_URL);
        doDownLoad(urlStr);
    }

    private void doDownLoad(String urlStr){
        PatchManager mPatchManager;
        OutputStream output=null;
        try {
            mPatchManager = new PatchManager(this);
            URL url = new URL(urlStr);
            HttpURLConnection conn=(HttpURLConnection)url.openConnection();
            //String SDCard= Environment.getExternalStorageDirectory()+"";
            String SDCard=  getApplicationContext().getFilesDir().getPath();
            String pathName=SDCard+"/"+PATCH+"/"+FILE_NAME;//文件存储路径

           Log.e("=========", "pathName = "+pathName);
            File file=new File(pathName);
            InputStream input=conn.getInputStream();
            if(file.exists()){
                file.delete();
            }
            String dir=SDCard+"/"+PATCH;
            new File(dir).mkdir();//新建文件夹
            file.createNewFile();//新建文件
            output=new FileOutputStream(file);
            //读取大文件
            byte[] buffer=new byte[4*1024];
            
            int len; 
            while((len =input.read(buffer))!=-1){
            	 output.write(buffer,0,len);
            }
            if (output!=null) {
            	output.close();
			}
            if (input!=null) {
            	input.close(); 
			}
            
            mPatchManager.addPatch(pathName);
            mHandler.sendEmptyMessage(0);
            
        } catch (Exception e) {
        	Message msg = Message.obtain(); 
            msg.what = 1;
            msg.obj = urlStr;
            mHandler.sendMessage(msg);
          
        }
    }
    private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case 0:
				CommonUtils.setApatchCode(getApplicationContext(), ""+CommonUtils.getAppVersionCode(getApplicationContext()));
				CommonUtils.setFailApatchCode(getApplicationContext(), "");
				CommonUtils.setFailApatchUrl(getApplicationContext(), "");
				showDialog();
				break;
			case 1:
				CommonUtils.setFailApatchCode(getApplicationContext(), ""+CommonUtils.getAppVersionCode(getApplicationContext()));
				CommonUtils.setFailApatchUrl(getApplicationContext(), (String)msg.obj);
				break;
			default:
				break;
		}
	}
};
			
    
    private void showDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getApplicationContext());
        
        
        final AlertDialog mDialog = builder.create();
        
        Window window = mDialog.getWindow();
        window.setBackgroundDrawable(new ColorDrawable(0));  
        //在dialog  show方法之前添加如下代码，表示该dialog是一个系统的dialog**
        mDialog.getWindow().setType((WindowManager.LayoutParams.TYPE_SYSTEM_ALERT));
        mDialog.show();
        window.setContentView(R.layout.view_dialog);
        
        TextView dialogTitle = (TextView) window.findViewById(R.id.title);
        TextView dialogContent = (TextView) window.findViewById(R.id.content);
        dialogTitle.setText("温馨提示");
        dialogContent.setText("应用更新完成，重启后生效！");
        Button confirm = (Button) window.findViewById(R.id.ok);
        Button cancels = (Button) window.findViewById(R.id.res);
        mDialog.setCanceledOnTouchOutside(false);
        confirm.setText("重启");
        confirm.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View view) {
            	 CommonUtils.restartAPP(getApplicationContext(),100);
            	 mDialog.dismiss();
             }
        });
        cancels.setText("取消");
        cancels.setOnClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View view) {
            	 mDialog.dismiss();
             }
        });

        
    }

    
	
    
}
